import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import 'package:kq_flutter_widgets/resources/kq_theme_colors.dart';
import 'package:kq_flutter_widgets/utils/dialog_util.dart';
import 'package:kq_flutter_widgets/utils/kq_form_util.dart';
import 'package:kq_flutter_core_widget/utils/text_input_format_utils.dart';
import 'package:kq_flutter_core_widget/utils/toast_util.dart';
import 'package:kq_flutter_widgets/widgets/button/kq_bottom_button.dart';
import 'package:kq_flutter_widgets/widgets/button/kq_small_button.dart';
import 'package:kq_flutter_widgets/widgets/formItem/entity/kq_form_entity.dart';
import 'package:kq_flutter_widgets/widgets/formItem/kq_checkbox_item_view.dart';
import 'package:kq_flutter_widgets/widgets/formItem/kq_radio_item_view.dart';
import 'package:kq_flutter_widgets/widgets/scaffold/kq_scaffold.dart';
import 'package:kq_flutter_widgets/widgets/titleBar/kq_title_bar.dart';

/// 表单演示
class FormDemoPage extends StatefulWidget {
  const FormDemoPage({Key? key}) : super(key: key);

  @override
  _FormDemoPageState createState() => _FormDemoPageState();
}

class _FormDemoPageState extends State<FormDemoPage> {
  List<KqFormEntity> data = [];

  @override
  void initState() {
    _initData();

    super.initState();
  }

  _initData() {
    /// 其他控件数据
    data = [
      KqFormEntity(
          itemType: ItemType.edit,
          title: '单行输入',
          mustInput: true,
          contentKey: 'contentKey1',
          inputFormatters: TextInputFormatUtils.maxInter(100),
          enableClearButton: false),
      KqFormEntity(
          itemType: ItemType.edit,
          title: '标题很长很长很长很长很长',
          contentKey: 'contentKey2'),
      KqFormEntity(
          itemType: ItemType.edit,
          title: '输入带单位',
          contentKey: 'contentKey3',
          unit: 'kg'),
      KqFormEntity(itemType: ItemType.empty),
      KqFormEntity(
          title: '选择',
          contentKey: 'contentKey4',
          itemType: ItemType.select,
          itemId: 'contentKey4',
          mustInput: true,
          onTap: (entity) {
            KqDialog.showListDialog(
              ['item1', 'item2', 'item3很长很长很长很长很长很长很长很长很长很长很长很长'],
              callback: (index, item) {
                entity.valueForSubmit = item;
                entity.valueForShow = item;
                entity.unit = '(共3条)';
                entity.widgetState.update();
              },
            );
          }),
      KqFormEntity(
        title: '纯数量',
        contentKey: 'contentKey5',
        minQty: 0.5,
        qty: 0.5,
        maxQty: 100.6,
        qtyStep: 2.5,
        itemType: ItemType.onlyNumber,
        inputType: const TextInputType.numberWithOptions(decimal: true),
        inputFormatters: TextInputFormatUtils.decimal(),
        mustInput: true,
      ),
      KqFormEntity(title: '分类', itemType: ItemType.header),
      KqFormEntity(
        itemType: ItemType.edit,
        title: '多行输入',
        contentKey: 'contentKey6',
        multiline: true,
        onSubmitted: (value) {
          KqToast.showNormal('1111');
        },
      ),
      KqFormEntity(
        itemType: ItemType.radio,
        title: '单选',
        mustInput: true,
        editable: true,
        contentKey: 'contentKey7',
        radioData: [
          RadioData(item: '男', itemId: '0'),
          RadioData(item: '女', itemId: '1'),
        ],
        onRadioChanged: (entity, radioData) => KqToast.showNormal(
            '${entity.valueForShow},${entity.valueForSubmit}'),
      ),
      KqFormEntity(
        itemType: ItemType.radio,
        title: '单选非编辑',
        mustInput: true,
        editable: false,
        contentKey: 'contentKey7',
        valueForSubmit: '0',
        radioData: [
          RadioData(item: '男', itemId: '0'),
          RadioData(item: '女', itemId: '1'),
        ],
        onRadioChanged: (entity, radioData) => KqToast.showNormal(
            '${entity.valueForShow},${entity.valueForSubmit}'),
      ),
      KqFormEntity(
        itemType: ItemType.radio,
        title: '单选不可编辑',
        mustInput: true,
        editable: true,
        contentKey: 'contentKey7',
        titleColor: KqThemeColors.textBF,
        valueForSubmit: '0',
        radioData: [
          RadioData(item: '男', itemId: '0', disabled: true),
          RadioData(item: '女', itemId: '1', disabled: true),
        ],
        onRadioChanged: (entity, radioData) => KqToast.showNormal(
            '${entity.valueForShow},${entity.valueForSubmit}'),
      ),
      KqFormEntity(
        itemType: ItemType.checkbox,
        title: '多选',
        mustInput: true,
        editable: true,
        contentKey: 'contentKey7',
        checkBoxData: [
          CheckBoxData(item: '填写', itemId: '0', checked: true),
          CheckBoxData(item: '未填写', itemId: '1')
        ],
        willUnCheckAll: () {
          KqToast.showNormal('填写和未填写至少填一个');
          return true;
        },
        onCheckBoxChanged: (entity, checkboxData) {
          print(entity.valueForSubmit);
        },
      ),
      KqFormEntity(
        itemType: ItemType.edit,
        title: '自定义输入右边布局',
        contentKey: 'contentKey8',
        customRightView: (entity) {
          return Container(
            padding: EdgeInsets.only(left: 10.r),
            child: KqSmallButton(
              title: '自动生成',
              onTap: (disabled) {
                entity.valueForShow = '选择内容1';
                entity.valueForSubmit = '选择内容1';
                entity.widgetState.update();
              },
            ),
          );
        },
      ),
      KqFormEntity(
        title: '自定义右侧控件',
        extraData: false,
        itemType: ItemType.custom,
        onTap: (entity) {
          entity.extraData = !entity.extraData;
          entity.widgetState.update();
        },
        customRightView: (entity) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [Text('这里可以放任意内容')],
          );
        },
      ),
      KqFormEntity(
        title: '开关封装',
        checked: false,
        contentKey: 'contentKey9',
        itemType: ItemType.switcher,
        onCheckedChanged: (value) {
          KqToast.showNormal('$value');
          var item = KqFormUtil.findEntityByItemId(data, 'contentKey4');
          item?.visible = value;
          item?.updateWidget();
        },
      ),
      KqFormEntity(
        title: '数字组合控件',
        unit: '测试单位长',
        itemType: ItemType.addNumber,
        extraData: [
          KqFormQtyEntity(
              valueForShow: '测试不可编辑1', editable: false, qty: 10, unit: '个'),
        ],
        onQtyTap: (entity, entityQty) {
          entityQty.valueForShow = '选择内容1';
          entityQty.valueForSubmit = '选择内容1';
          entity.widgetState.update();
        },
      ),
      KqFormEntity(
        title: '上下限',
        unit: 'kg',
        mustInput: true,
        itemType: ItemType.editUpperLower,
        valuesForShow: ['12', null],
        contentKey: 'UpperLower',
        contentKeyForChild: [
          'Lower',
          'Upper',
        ],
      ),
      KqFormEntity(
        title: '图片上传',
        itemType: ItemType.imageBox,
        mustInput: true,
        contentKey: 'contentKey10',
        imageUrls: [],
        // 这三个方法不实现，则默认拍照会选择本地图片，valueForSubmit需要自己在提交时处理。
        // onAddTap: (entity, state) async {
        //   KqUpload.getInstance()?.handleUpload(
        //     context,
        //     (files) {
        //       for (var file in files) {
        //         /// valueForSubmit 用于存放给后端的数据，比如选完图片立即上传给后端
        //         state.addImage(ImageUrl(
        //             imageType: ImageType.file,
        //             url: file.filePath!,
        //             valueForSubmit: '111'));
        //       }
        //       // 这里看后端需要什么自己处理提交给后端的数据结构，这里只是举个例子
        //       entity.valueForSubmit = state.getSubmitValues();
        //     },
        //   );
        //   // 网络图片
        //   // state.addImage(ImageUrl(
        //   //     imageType: ImageType.http,
        //   //     url:
        //   //         'https://img0.baidu.com/it/u=2495824266,2372368334&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1677517200&t=2f308f262a4320220400c4366817b698'));
        // },
        // onDeleteTap: (entity, imageUrl, position, state) {
        //   state.remove(imageUrl);
        //   entity.valueForSubmit = state.getSubmitValues();
        // },
        // onImageTap: (entity, imageUrl, position, state) {
        //   KqToast.showNormal('你点击了第${position + 1}张图片');
        //   FilePreviewUtil.previewImg(entity.imageUrls!);
        // },
      ),
    ];
  }

  /// 通用组件渲染逻辑
  List<Widget> _buildWidget() {
    if (data.isEmpty) {
      return [];
    }
    return KqFormUtil.renderFormWidgetList(data);
  }

  void _submitData() {
    if (KqFormUtil.checkMustInputForm(data)) {
      return;
    }
    var map = KqFormUtil.getFormSubmitJson(data);
    KqToast.showNormal(map.toString());
  }

  @override
  Widget build(BuildContext context) {
    return KqScaffold(
      appBar: KqHeadBar(
        headTitle: '表单组件演示',
      ),
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: [..._buildWidget()],
              ),
            ),
          ),
          if (!context.keyboardVisible)
            KqBottomButton(
              title: '提交',
              onTap: (disabled) {
                _submitData();
              },
            )
        ],
      ),
    );
  }
}
